import 'dart:async';
import 'dart:convert';
import 'dart:ffi';
import 'dart:math';
import 'package:awesome_dialog/awesome_dialog.dart';
import 'package:convert/convert.dart';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_reader/dao/book_collect_data_manager.dart';
import 'package:flutter_reader/dao/me_data_manager.dart';
import 'package:flutter_reader/model/book/book_collect_model.dart';
import 'package:flutter_reader/model/book/bookshelf_model.dart';
import 'package:flutter_reader/pages/book_shelf/bookshelf_page.dart';
import 'package:flutter_reader/pages/category/category_page.dart';
import 'package:flutter_reader/pages/read_book/book_catelog.dart';
import 'package:flutter_reader/pages/read_book/book_content.dart';
import 'package:flutter_reader/pages/read_book/book_introduction.dart';
import 'package:flutter_reader/tools/dot_type.dart';
import 'package:flutter_reader/tools/point_loader.dart';
import 'package:flutter_reader/widget/book_hero.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_udid/flutter_udid.dart';
import 'package:notification_permissions/notification_permissions.dart';
import 'package:package_info/package_info.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:flutter_reader/tools/globals.dart' as globals;
import 'dart:io' show Platform;

import 'package:url_launcher/url_launcher.dart';

class bookShelfDetailPage extends StatefulWidget {
  final bool _isEditing ;

  final Stream shouldTriggerChange;

  bookShelfDetailPage(this._isEditing,this.shouldTriggerChange);


  @override
  _bookShelfDetailPageState createState() {
    return _bookShelfDetailPageState();
  }
}

class _bookShelfDetailPageState extends State<bookShelfDetailPage>  {

  bool _hasBook = true;
  bool _isLoadingBook = true;
  BookShelfModel _bookShelfModel;
  List<BookShelfData> _bookShelfData = [];
  List<String> _bookId = [];
  List<String> _bookName = [];
  List<String> _bookImage = [];

  List<bool> someBooleanValue = [];

  List<String> toDelete = [];

  StreamSubscription streamSubscription;

  int books = 0;


  //应用权限相关
  Future<String> permissionStatusFuture;

  var permGranted = "granted";
  var permDenied = "denied";
  var permUnknown = "unknown";

  @override
  void initState() {
    // initPlatformState();
    const oneSec = const Duration(seconds:1);
    new Timer.periodic(oneSec, (Timer t){
      if(globals.fullSessionID == null){

      }
      else{
        if(globals.needAddBook == true)
          {
            addRecommendBook();
            globals.needAddBook = false;
          }
        loadBook();
        t.cancel();
      }
    });
    streamSubscription = widget.shouldTriggerChange.listen((_) => reload());
    super.initState();
    permissionStatusFuture = getCheckNotificationPermStatus();
    requestPermission();
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    if (state == AppLifecycleState.resumed) {
      setState(() {
        permissionStatusFuture = getCheckNotificationPermStatus();
      });
    }
  }


  ///请求通知权限
  Future<String> getCheckNotificationPermStatus() {
    return NotificationPermissions.getNotificationPermissionStatus()
        .then((status) {
      switch (status) {
        case PermissionStatus.denied:
          return permDenied;
        case PermissionStatus.granted:
          return permGranted;
        case PermissionStatus.unknown:
          return permUnknown;
        default:
          return null;
      }
    });
  }

  requestPermission() {
    permissionStatusFuture.then((value) {
      print("权限-----------------${value.toString()}");
      if (value.toString() == 'denied') {
        AwesomeDialog(
          context: context,
          animType: AnimType.SCALE,
          dialogType: DialogType.INFO,
          btnOkText: "现在就去",
          btnCancelText: "稍后再说",
          desc: "开启推送功能，接收更多精彩内容",
          tittle: "开启推送",
          btnCancelOnPress: () {
            Navigator.of(context).popUntil((route) => route.isFirst);
            checkVersion();
          },
          btnOkOnPress: () {
            NotificationPermissions
                .requestNotificationPermissions(
                iosSettings:
                const NotificationSettingsIos(
                    sound: true,
                    badge: true,
                    alert: true))
                .then((_) {
              // when finished, check the permission status
              setState(() {
                permissionStatusFuture =
                    getCheckNotificationPermStatus();
              });
            });
          },
        ).show();
      }
      else
        {
          checkVersion();
        }
    });
  }

  ///检查版本更新
  checkVersion() async{
    MeDao.checkVersion().then((value){
      if(value["data"]["content"] != null)
        {
          if(value["data"]["force"] == true)
            {
              AwesomeDialog(
                context: context,
                animType: AnimType.SCALE,
                dialogType: DialogType.INFO,
                btnOkText: "马上下载",
                btnCancelText: "稍后再说",
                desc: value["data"]["content"],
                tittle: "检测到新版本",
                btnOkOnPress: () async{
                  String url = value["data"]["url"];
                  if (await canLaunch(url)) {
                    await launch(url);
                  } else {
                    throw 'Could not launch $url';
                  }
                  needDialog();
                },
                btnCancelOnPress: (){
                  Navigator.of(context).popUntil((route) => route.isFirst);
                  needDialog();
                }
              ).show();
            }
          else
            {
              AwesomeDialog(
                context: context,
                animType: AnimType.SCALE,
                dialogType: DialogType.INFO,
                btnOkText: "马上下载",
                btnCancelText: "稍后再说",
                desc: value["data"]['content'],
                tittle: "检测到新版本",
                btnCancelOnPress: () {
                  Navigator.of(context).popUntil((route) => route.isFirst);
                  needDialog();
                },
                btnOkOnPress: () async{
                  String url = value["data"]["url"];
                  if (await canLaunch(url)) {
                    await launch(url);
                  } else {
                    throw 'Could not launch $url';
                  }
                  needDialog();
                },
              ).show();
            }
        }
      else
        {
          ///已经是最新版本
          needDialog();
        }
    });
  }


  needDialog() async{
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    bool goOther = sharedPreferences.getBool("goOther");
    int dialog = sharedPreferences.getInt("dialog") ?? 0;
    print(dialog);
    print("dialog: ----------${dialog.toString()}");
    print("goOther: -------${goOther.toString()}");
    if(goOther == false && dialog > 0)
    {
      WidgetsBinding.instance.addPostFrameCallback((_) async {
        await showGeneralDialog(
            context: context,
            barrierDismissible: true,
            barrierLabel: MaterialLocalizations.of(context)
                .modalBarrierDismissLabel,
            barrierColor: Colors.black45,
            transitionDuration: const Duration(milliseconds: 200),
            pageBuilder: (BuildContext buildContext,
                Animation animation,
                Animation secondaryAnimation) {
              return Material(
                color: Colors.black38,
                child: Center(
                  child: Container(
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.all(Radius.circular(10)),
                      color: Colors.white,
                    ),
                    width: ScreenUtil().setWidth(1000),
                    height: ScreenUtil().setHeight(900),
                    padding: EdgeInsets.only(top: ScreenUtil().setHeight(40)),
                    child: Column(
                      children: [
                        Container(
                          margin: EdgeInsets.only(top: ScreenUtil().setHeight(30)),
                          width: ScreenUtil().setWidth(900),
                          height: ScreenUtil().setHeight(180),
                          child:  Center(
                            child: FittedBox(
                              fit: BoxFit.fitHeight,
                              child: Text(
                                "点击下方红字继续阅读",
                                style: TextStyle(
                                    fontWeight: FontWeight.w600
                                ),
                              ),
                            ),
                          ),
                        ),
                        InkWell(
                          onTap: (){
                            Navigator.push(context, MaterialPageRoute(
                                builder: (context) => BookContentPage("B9A04E1D19B8D1D747DF70364B08CA6B","D2E941B0E38A097A110A920CB0B9C475",true)
                            )).then((value){
                              needDialog();
                            });
                          },
                          child: Container(
                            width: ScreenUtil().setWidth(900),
                            height: ScreenUtil().setHeight(130),
                            child: Center(
                              child: FittedBox(
                                fit: BoxFit.fitHeight,
                                child: Text(
                                  '......赵兰......',
                                  style: TextStyle(
                                      color: Colors.redAccent
                                  ),
                                ),
                              ),
                            ),
                          ),
                        ),
                        InkWell(
                          onTap: (){
                            Navigator.push(context, MaterialPageRoute(
                                builder: (context) => BookContentPage("275D35386BC6721EB949B5483B974528","84101F8BF73334E10D400EAAE33FB71B",true)
                            )).then((value){
                              needDialog();
                            });
                          },
                          child: Container(
                            width: ScreenUtil().setWidth(900),
                            height: ScreenUtil().setHeight(130),
                            child: Center(
                              child: FittedBox(
                                fit: BoxFit.fitHeight,
                                child: Text(
                                  '......旅游......',
                                  style: TextStyle(
                                      color: Colors.redAccent
                                  ),
                                ),
                              ),
                            ),
                          ),
                        ),
                        InkWell(
                          onTap: (){
                            Navigator.push(context, MaterialPageRoute(
                                builder: (context) => BookContentPage("8BEC74DAEA6F132E8217B5F41D7C2651","34F73CA6C7AC6C6A2B54465AB251CAE0",true)
                            )).then((value){
                              needDialog();
                            });
                          },
                          child: Container(
                            width: ScreenUtil().setWidth(900),
                            height: ScreenUtil().setHeight(130),
                            child: Center(
                              child: FittedBox(
                                fit: BoxFit.fitHeight,
                                child: Text(
                                  '......苏柔......',
                                  style: TextStyle(
                                      color: Colors.redAccent
                                  ),
                                ),
                              ),
                            ),
                          ),
                        ),
                        Container(
                          margin: EdgeInsets.only(top: ScreenUtil().setHeight(60)),
                          width: ScreenUtil().setWidth(900),
                          child: Center(
                            child: RaisedButton(
                              shape: new RoundedRectangleBorder(
                                  borderRadius: new BorderRadius.circular(18.0),
                                  side: BorderSide(color: Colors.red)),
                              onPressed: () {
                                Navigator.pop(context);
                              },
                              color: Colors.red,
                              textColor: Colors.white,
                              child: Container(
                                width: ScreenUtil().setWidth(300),
                                child: Center(
                                  child: Text("稍后再看".toUpperCase(),
                                      style: TextStyle(fontSize: ScreenUtil().setSp(40))),
                                ),
                              ),
                            ),

                          ),
                        )
                      ],
                    ),
                  ),
                ),
              );
            });

      });
      dialog = dialog - 1;
      sharedPreferences.setInt("dialog", dialog);
    }
    else
    {

    }
  }

  goOther() async{
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    sharedPreferences.setBool("goOther", true);
  }

  showMyDialog(){
    return showGeneralDialog(
        context: context,
        barrierDismissible: true,
        barrierLabel: MaterialLocalizations.of(context)
            .modalBarrierDismissLabel,
        barrierColor: Colors.black45,
        transitionDuration: const Duration(milliseconds: 200),
        pageBuilder: (BuildContext buildContext,
            Animation animation,
            Animation secondaryAnimation) {
          return Material(
            color: Colors.black38,
            child: Center(
              child: Container(
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.all(Radius.circular(10)),
                  color: Colors.white,
                ),
                width: ScreenUtil().setWidth(1000),
                height: ScreenUtil().setHeight(900),
                padding: EdgeInsets.only(top: ScreenUtil().setHeight(40)),
                child: Column(
                  children: [
                    Container(
                      margin: EdgeInsets.only(top: ScreenUtil().setHeight(60)),
                      width: ScreenUtil().setWidth(900),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: <Widget>[
                          RaisedButton(
                            shape: new RoundedRectangleBorder(
                                borderRadius: new BorderRadius.circular(15.0),
                                side: BorderSide(width: 1,color: Colors.redAccent)
                            ),
                            onPressed: () {},
                            color: Colors.white,
                            textColor: Colors.redAccent,
                            child: Container(
                              width: ScreenUtil().setWidth(300),
                              child: Center(
                                child: Text("加入书架".toUpperCase(),
                                    style: TextStyle(fontSize: ScreenUtil().setSp(40))),
                              ),
                            ),
                          ),
                          RaisedButton(
                            shape: new RoundedRectangleBorder(
                                borderRadius: new BorderRadius.circular(18.0),
                                side: BorderSide(color: Colors.red)),
                            onPressed: () {
                              Navigator.pop(context);
                            },
                            color: Colors.red,
                            textColor: Colors.white,
                            child: Container(
                              width: ScreenUtil().setWidth(300),
                              child: Center(
                                child: Text("继续阅读".toUpperCase(),
                                    style: TextStyle(fontSize: ScreenUtil().setSp(40))),
                              ),
                            ),
                          ),
                        ],
                      ),
                    )
                  ],
                ),
              ),
            ),
          );
        });
  }

  ///集成极光推送
  String debugLable = 'Unknown';
  // final JPush jpush = new JPush();

  // Future<void> initPlatformState() async {
  //   String platformVersion;
  //   try {
  //     jpush.addEventHandler(
  //       onReceiveNotification: (Map<String, dynamic> message) async {
  //         print("flutter onReceiveNotification: $message");
  //         setState(() {
  //           debugLable = "flutter onReceiveNotification: $message";
  //         });
  //       },
  //       onOpenNotification: (Map<String, dynamic> message) async {
  //         print('通知栏打开');
  //         print("flutter onOpenNotification: $message");
  //         print("${message["extras"]}");
  //         print("${message["extras"]["cn.jpush.android.EXTRA"]}");
  //         Map aa = json.decode(message["extras"]["cn.jpush.android.EXTRA"]);
  //         print("${aa["bookID"]}");
  //         Navigator.push(context, MaterialPageRoute(
  //             builder: (context) => BookInfoPage(bookId: aa["bookID"],channel: "1",)
  //         ));
  //       },
  //       onReceiveMessage: (Map<String, dynamic> message) async {
  //         print("flutter onReceiveMessage: $message");
  //         setState(() {
  //           debugLable = "flutter onReceiveMessage: $message";
  //         });
  //       },
  //     );
  //   } on PlatformException {
  //     platformVersion = 'Failed to get platform version.';
  //   }
  //
  //
  //   jpush.setup(
  //     appKey: "adb5d6fcf5e4fb488ec47e9e",
  //     channel: "theChannel",
  //     production: false,
  //     debug: true,
  //   );
  //   jpush.applyPushAuthority(new NotificationSettingsIOS(
  //       sound: true,
  //       alert: true,
  //       badge: true));
  //
  //
  //   // Platform messages may fail, so we use a try/catch PlatformException.
  //   jpush.getRegistrationID().then((rid) {
  //     print("flutter get registration id : $rid");
  //     setState(() {
  //       debugLable = "flutter getRegistrationID: $rid";
  //     });
  //   });
  //
  //
  //   // If the widget was removed from the tree while the asynchronous platform
  //   // message was in flight, we want to discard the reply rather than calling
  //   // setState to update our non-existent appearance.
  //   if (!mounted) return;
  //
  //   setState(() {
  //     debugLable = platformVersion;
  //   });
  // }

///新增推荐书籍
  addRecommendBook(){
    print("添加推荐书");
    BookCollectDao.getForCollect("84101F8BF73334E10D400EAAE33FB71B");
    Future.delayed(const Duration(milliseconds: 100), (){
      BookCollectDao.getForCollect("34F73CA6C7AC6C6A2B54465AB251CAE0");
      Future.delayed(const Duration(milliseconds: 100),(){
        BookCollectDao.getForCollect("D2E941B0E38A097A110A920CB0B9C475");
      });
    });
  }

  @override
  didUpdateWidget(bookShelfDetailPage old) {
    super.didUpdateWidget(old);
    // in case the stream instance changed, subscribe to the new one
    if (widget.shouldTriggerChange != old.shouldTriggerChange) {
      streamSubscription.cancel();
      streamSubscription = widget.shouldTriggerChange.listen((_) => loadBook());
    }
  }


  @override
  void dispose() {
    streamSubscription.cancel();
    goOther();
    super.dispose();
  }



  saveData() async {
    SharedPreferences preferences = await SharedPreferences.getInstance();
    preferences.setStringList("toDelete", toDelete);
  }


  loadBook(){
    print('load');
    _isLoadingBook = true;
    _bookId.clear();
    _bookName.clear();
    _bookImage.clear();
    new Timer(new Duration(milliseconds: 1000), ()
    {
      BookCollectDao.fetchBookShelf().then((value) {
        if (value['data'] == null) {
          setState(() {
            _hasBook = false;
          });
        }
        else {
          print(value['data'][0]['name']);
          setState(() {
            books = value['data'].length;
            for (int i = 0; i < value['data'].length; i++) {
              _bookId.add(value['data'][i]['id']);
              _bookName.add(value['data'][i]['name']);
              _bookImage.add(value['data'][i]['image']);
            }
            print(_bookName);
            _hasBook = true;
          });
        }
        _isLoadingBook = false;
      });
    });
  }

  reload(){
    print('load');
    for(int i = 0 ;i<toDelete.length; i++){
      someBooleanValue.removeAt(int.parse(toDelete[i]));
    }
    toDelete = [];
    saveData();
    _isLoadingBook = true;
    _bookId.clear();
    _bookName.clear();
    _bookImage.clear();
    BookCollectDao.fetchBookShelf().then((value){
      if(value['data'] == null){
        setState(() {
          _hasBook = false;
        });
      }
      else{
        setState(() {
          print(value['data'][0]['name']);
          books = value['data'].length;
          for (int i = 0; i < value['data'].length; i++) {
            _bookId.add(value['data'][i]['id']);
            _bookName.add(value['data'][i]['name']);
            _bookImage.add(value['data'][i]['image']);
          }
          _hasBook = true;
        });
      }
      _isLoadingBook = false;
    });
  }


  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      body: _hasBook == false ? Container(
          margin: EdgeInsets.only(top: ScreenUtil().setHeight(200)),
          child: Center(
              child: Column(
                children: <Widget>[
                  Padding(
                      padding: EdgeInsets.only(left: ScreenUtil().setWidth(0)),
                      child: Image(
                        height: ScreenUtil().setHeight(400),
                        width: ScreenUtil().setWidth(350),
                        image: AssetImage('images/fl_nobook.png'),
                      )
                  ),
                  Padding(
                    padding: EdgeInsets.fromLTRB(
                        0,
                        ScreenUtil().setHeight(15),
                        0,
                        ScreenUtil().setHeight(10)),
                    child: Text(
                      '暂无书籍',
                      style: TextStyle(
                          fontSize: ScreenUtil().setSp(50),
                          color: Colors.black54
                      ),
                    ),
                  ),
                  Container(
                      margin: EdgeInsets.fromLTRB(
                          ScreenUtil().setWidth(25),
                          ScreenUtil().setHeight(100),
                          0,
                          ScreenUtil().setHeight(0)
                      ),
                      child: SizedBox(
                          width: ScreenUtil().setWidth(500),
                          height: ScreenUtil().setHeight(130),
                          child: RaisedButton(
                            onPressed: (){
                              Navigator.push(
                                  context,
                                  MaterialPageRoute(
                                      builder:
                                          (context) => CategoryPage()
                                  )
                              );
                            },
                            color: Color(0xffe53935),
                            shape: RoundedRectangleBorder(
                                borderRadius: BorderRadius.circular(20)
                            ),
                            textColor: Colors.white,
                            child: Text(
                              '去书城看看',
                              style: TextStyle(
                                fontSize: ScreenUtil().setSp(50),
                              ),
                            ),
                          )
                      )
                  )
                ],
              )
          )
      ) :
      _isLoadingBook == true ? Container(
        height: ScreenUtil().setHeight(1800),
        width: ScreenUtil().setWidth(1125),
        child: Center(
          child: ColorLoader4(
            dotOneColor: Colors.pink,
            dotTwoColor: Colors.amber,
            dotThreeColor: Colors.deepOrange,
            dotType: DotType.square,
            duration: Duration(seconds: 2),
          )
        ),
      ) : SingleChildScrollView(
    child: Container(
    child: GridView.builder(
    shrinkWrap: true,
    itemCount: books,
    physics: NeverScrollableScrollPhysics(),
    padding: EdgeInsets.symmetric(horizontal: 0),
    gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
    crossAxisCount: 3,
    mainAxisSpacing: 0,
    crossAxisSpacing: 0,
    childAspectRatio: 0.65,
    ),
    itemBuilder: (context,index){
    return _subItem(_bookId[index], _bookImage[index], _bookName[index], index);
    },
    ),
    ),
    ),
    );
  }

  _subItem(String bookId, String image, String title, int index){
    someBooleanValue.add(false);
    return widget._isEditing ? Container(
          margin: EdgeInsets.only(left: ScreenUtil().setWidth(5)),
          width: ScreenUtil().setWidth(310),
          padding: EdgeInsets.only(top: ScreenUtil().setHeight(40)),
          child: Column(
            children: <Widget>[
              Stack(
                children: <Widget>[
                  Container(
                    width: 0.8*ScreenUtil().setHeight(400),
                    height: ScreenUtil().setHeight(400),
                    decoration: BoxDecoration(
                      boxShadow: <BoxShadow>[
                        new BoxShadow(
                          color: Colors.black54,
                          blurRadius: 5.0,
                          spreadRadius: 1.0,
                          offset: Offset(-2.0, 2.0),
                        ),
                      ],
                    ),
                    child: Image(
                      image: NetworkImage(image),
                    ),
                  ),
                  Container(
                    color: Color.fromRGBO(0, 0, 0, 0.3),
                    width: 0.8*ScreenUtil().setHeight(400),
                    height: ScreenUtil().setHeight(400),
                    child: Center(
//                      child: CircularCheckBox(
//                        inactiveColor: Colors.white,
//                          value: someBooleanValue[index],
//                          materialTapTargetSize: MaterialTapTargetSize.padded,
//                          onChanged: (bool x) {
//                            setState(() {
//                              someBooleanValue[index] = !someBooleanValue[index];
//                            });
//                            if(someBooleanValue[index] == true){
//                              toDelete.add(index.toString());
//                            }
//                            else
//                            {
//                              toDelete.removeAt(index);
//                            }
//                            saveData();
//                          }
//                      ),
                    ),
                  )
                ],
              ),
              Container(
                  width: ScreenUtil().setWidth(300),
                  margin: EdgeInsets.only(top: ScreenUtil().setHeight(35)),
                  child:Center(
                    child: Text(
                      title,
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                    ),
                  )
              )
            ],
          ),
        ) : Container(
      margin: EdgeInsets.only(left: ScreenUtil().setWidth(5)),
      width: ScreenUtil().setWidth(310),
      padding: EdgeInsets.only(top: ScreenUtil().setHeight(40)),
      child: Column(
        children: <Widget>[
          BookHero(
              book: image,
              height: ScreenUtil().setHeight(400),
              callback: (){
                Navigator.of(context).push(MaterialPageRoute<void>(
                    builder: (BuildContext context){
                      return BookInfoPage(channel: '1',bookId: bookId,bookName: title,bookImage: image,isHorizontal: false,hasCollect: false,);
                    }
                )).then((value){
                  needDialog();
                });
              }
          ),
          Container(
            width: ScreenUtil().setWidth(300),
              margin: EdgeInsets.only(top: ScreenUtil().setHeight(35)),
              child:Center(
                child: Text(
                  title,
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                ),
              )
          )
        ],
      ),
    );
  }

}